import React from 'react';
import { Row, Col, Form, Input, Select, DatePicker, Radio, Alert, Button } from 'antd';
import moment from 'moment';
import cn from 'classnames';
import { get as getPath } from 'object-path';
import { UploadOssCompact } from '@/containers';
import { AutoCompleteSelect } from './components';
import {
    backgroundTypeMap,
    objectContactTypeList,
    objectContactTypeMap,
    // phoneAreaTextMap,
    feedbackStateInfo
} from '../utils';
import styles from './index.less';

const FormContainer = ({ children, colProps = {} }) => {
    const childrenArray = React.Children.toArray(children);
    return childrenArray.map(item => (
        <Col
            xs={{ span: 24 }}
            sm={{ span: 24 }}
            md={{ span: getPath(item, 'props.span', null) || 12 }}
            {...colProps}
            key={item.key}
        >
            {item}
        </Col>
    ));
};

const OrganizationNameItem = props => {
    const {
        canOnlyEditEvaluate = false,
        bgCompanyList = [],
        label,
        inputRules,
        form,
        dynamicKey: key = '',
        isDetail = false,
        dataList,
        placeholder,
        initialFormInfo = {}
    } = props;
    const { getFieldDecorator } = form;
    return (
        <Form.Item required={!isDetail} label={label} key={`organizationName-${key}`}>
            {!isDetail &&
                getFieldDecorator(`organizationName-${key}`, {
                    initialValue: initialFormInfo.organizationName,
                    rules: inputRules(label, true)
                })(
                    <AutoCompleteSelect
                        disabled={canOnlyEditEvaluate}
                        dataList={dataList || bgCompanyList.map(item => ({ label: item, value: item }))}
                        placeholder={placeholder || '请选择或输入'}
                        allowClear
                    />
                )}
            {isDetail && <span>{initialFormInfo.organizationName}</span>}
        </Form.Item>
    );
};
const BackgroundTimeItem = props => {
    const {
        backgroundType,
        canOnlyEditEvaluate = false,
        form,
        dynamicKey: key = '',
        isDetail = false,
        initialFormInfo = {}
    } = props;
    const { getFieldDecorator } = form;
    return (
        <Form.Item required={!isDetail} label="背调时间" key={`backgroundTime-${key}`}>
            {!isDetail &&
                getFieldDecorator(`backgroundTime-${key}`, {
                    initialValue:
                        initialFormInfo.backgroundType === backgroundType && initialFormInfo.backgroundTime
                            ? moment(initialFormInfo.backgroundTime)
                            : undefined,
                    rules: [
                        {
                            required: true,
                            message: '请选择背调时间'
                        }
                    ]
                })(
                    <DatePicker
                        disabled={canOnlyEditEvaluate}
                        format="YYYY-MM-DD HH:mm"
                        showTime={{ format: 'HH:mm' }}
                        style={{ width: '100%' }}
                        placeholder="请选择背调时间"
                    />
                )}
            {isDetail && (
                <span>{initialFormInfo.backgroundTime ? initialFormInfo.backgroundTime?.slice(0, -3) : '无'}</span>
            )}
        </Form.Item>
    );
};
const EvaluateRemarkItem = props => {
    const {
        backgroundType,
        span,
        label,
        rules,
        fullRowLayout,
        form,
        dynamicKey: key = '',
        isDetail = false,
        initialFormInfo = {}
    } = props;
    const { getFieldDecorator } = form;
    return (
        <Form.Item span={span} {...fullRowLayout} label={label} key={`evaluateRemark-${key}`}>
            {!isDetail &&
                getFieldDecorator(`evaluateRemark-${key}`, {
                    initialValue:
                        initialFormInfo.backgroundType === backgroundType ? initialFormInfo.evaluateRemark : '',
                    rules: rules || [
                        {
                            required: false,
                            max: 1000,
                            message: '不能超过1000个字符'
                        }
                    ]
                })(<Input.TextArea maxLength={1000} rows={3} />)}
            {isDetail && <div className={styles.preText}>{initialFormInfo.evaluateRemark || '无'}</div>}
        </Form.Item>
    );
};

const BackgroundForm = props => {
    const {
        form,
        dynamicKey: key = '',
        isDetail = false,
        initialFormInfo = {},
        relateTypeList,
        isAddForm,
        setIsDetail,
        isAlert
    } = props;
    const { getFieldDecorator } = form;
    const [backgroundType, setBackgroundType] = React.useState(1);
    // const user = JSON.parse(localStorage.getItem('user') || {});
    // const isChinaArea = user?.areaCode === '86';
    // const defaultPhoneAreaType = isChinaArea ? 1 : 2;
    const [havePhoneAreaType, setHavePhoneAreaType] = React.useState(true);

    React.useEffect(() => {
        if (isDetail) {
            setBackgroundType(initialFormInfo.backgroundType);
        }
    }, [initialFormInfo.backgroundType, isDetail]);

    // modifyFlay : 可修改 0， 不可修改：1
    // 逻辑： 编辑背调记录时，如果modifyFlag为1,则只能编辑评价
    const canOnlyEditEvaluate = !isDetail && !isAddForm && initialFormInfo.modifyFlag === 1;

    React.useEffect(() => {
        const val = form.getFieldValue(`objectContactType-${key}`);
        if (Number(val) === 1) {
            if (!havePhoneAreaType) {
                setHavePhoneAreaType(true);
            }
        } else if (havePhoneAreaType) {
            setHavePhoneAreaType(false);
        }
    }, [form.getFieldValue(`objectContactType-${key}`)]);

    const inputRules = (label, required = false, isPureInput = false) => [
        {
            required,
            message: isPureInput ? `请输入${label}` : `请选择或输入${label}`
        },
        {
            min: 1,
            max: 50,
            message: '请输入1~50个字符'
        },
        {
            pattern: /^[^\s]+(\s+[^\s]+)*$/,
            message: '此处不能输入空格'
        }
    ];
    const fullRowLayout = {
        labelCol: {
            md: { span: 3 },
            xs: { span: 24 },
            sm: { span: 24 }
        },
        wrapperCol: {
            md: { span: 21 },
            xs: { span: 24 },
            sm: { span: 24 }
        }
    };

    const getContactText = () => {
        if (!initialFormInfo.objectContactInfo) {
            return '无';
        }
        // 临时去掉显示区号，后期需要添加区号，则放开
        // if (Number(initialFormInfo.objectContactType) === 1) {
        //     return `${objectContactTypeMap[initialFormInfo.objectContactType]} ${
        //         phoneAreaTextMap[initialFormInfo.phoneAreaType]
        //     } ${initialFormInfo.objectContactInfo}`;
        // }
        return `${objectContactTypeMap[initialFormInfo.objectContactType]} ${initialFormInfo.objectContactInfo}`;
    };

    const attachFileItem = () => {
        if (backgroundType === 2 && form.getFieldValue(`feedbackState-${key}`) === feedbackStateInfo[0].value) {
            return '';
        }
        // if (
        //     isDetail &&
        //     initialFormInfo.backgroundType === 2 &&
        //     initialFormInfo.feedbackState === feedbackStateInfo[0].value
        // ) {
        //     return '';
        // }
        if (isDetail && !initialFormInfo.uploadFileUrl) {
            return (
                <Form.Item label="背景资料" {...fullRowLayout}>
                    无
                </Form.Item>
            );
        }
        return (
            <Form.Item
                label="背调资料"
                extra={isDetail ? '' : '支持扩展名：.rar .zip .doc .docx .pdf .jpg等格式的附件，单个文件大小为20M以内'}
                {...fullRowLayout}
            >
                {getFieldDecorator(`uploadFileUrl-${key}`, {
                    initialValue:
                        initialFormInfo.backgroundType === backgroundType ? initialFormInfo.uploadFileUrl : '',
                    rules: []
                })(<UploadOssCompact rules={[{ max: 20 }, { length: 1 }]} editable={!isDetail} />)}
            </Form.Item>
        );
    };

    // const getDictName = dictValue => relateTypeList.find(item => item.dictValue === dictValue)?.dictName;

    const initFormData = val => {
        const isCurrentType = val === initialFormInfo.backgroundType;
        if (!isCurrentType) {
            form.setFieldsValue({
                [`organizationName-${key}`]: '',
                [`evaluateRemark-${key}`]: '',
                [`backgroundTime-${key}`]: undefined,
                [`uploadFileUrl-${key}`]: ''
            });
        } else {
            form.setFieldsValue({
                [`organizationName-${key}`]: initialFormInfo.organizationName,
                [`evaluateRemark-${key}`]: initialFormInfo.evaluateRemark,
                [`backgroundTime-${key}`]: initialFormInfo.backgroundTime
                    ? moment(initialFormInfo.backgroundTime)
                    : undefined,
                [`uploadFileUrl-${key}`]: initialFormInfo.uploadFileUrl
            });
        }
    };

    const isShowAlert = isAlert && !isAddForm;

    return (
        <div className={cn({ [styles.marginBottom0]: isDetail, [styles.marginBottom16]: !isDetail })}>
            {isShowAlert && (
                <div className={styles.alert}>
                    <Alert message="候选人已反馈背调联系人信息，请完成背调工作" type="warning" showIcon />
                    <Button
                        className={styles.alertBtn}
                        type="link"
                        size="small"
                        onClick={() => {
                            setIsDetail(false);
                        }}
                    >
                        完善资料
                    </Button>
                </div>
            )}
            <Row>
                <FormContainer>
                    <Form.Item {...fullRowLayout} span={24} label="背调类型" key={`backgroundType-${key}`}>
                        {!isDetail &&
                            getFieldDecorator(`backgroundType-${key}`, {
                                initialValue: initialFormInfo.backgroundType || 1,
                                rules: [
                                    {
                                        required: false,
                                        message: '请输入'
                                    }
                                ]
                            })(
                                // <Select
                                //     disabled={canOnlyEditEvaluate}
                                //     placeholder="请选择"
                                //     onChange={val => {
                                //         setBackgroundType(val);
                                //         initFormData(val);
                                //     }}
                                // >
                                //     {Object.keys(backgroundTypeMap).map(type => (
                                //         <Select.Option value={Number(type)} key={type}>
                                //             {backgroundTypeMap[type]}
                                //         </Select.Option>
                                //     ))}
                                // </Select>
                                <Radio.Group
                                    disabled={canOnlyEditEvaluate}
                                    onChange={e => {
                                        const val = e.target.value;
                                        setBackgroundType(val);
                                        initFormData(val);
                                    }}
                                >
                                    {Object.keys(backgroundTypeMap).map(type => (
                                        <Radio value={Number(type)} key={type}>
                                            {backgroundTypeMap[type]}
                                        </Radio>
                                    ))}
                                </Radio.Group>
                            )}
                        {isDetail && <span>{backgroundTypeMap[initialFormInfo.backgroundType]}</span>}
                    </Form.Item>
                </FormContainer>
            </Row>
            <Row gutter={5}>
                <>
                    {backgroundType === 1 && (
                        <FormContainer>
                            <OrganizationNameItem
                                canOnlyEditEvaluate={canOnlyEditEvaluate}
                                label="背调公司"
                                inputRules={inputRules}
                                {...props}
                            />
                            <Form.Item required={!isDetail} label="对象姓名" key={`objectName-${key}`}>
                                {!isDetail &&
                                    getFieldDecorator(`objectName-${key}`, {
                                        initialValue: initialFormInfo.objectName,
                                        rules: inputRules('对象姓名', true, true)
                                    })(<Input disabled={canOnlyEditEvaluate} placeholder="请输入" allowClear />)}
                                {isDetail && <span>{initialFormInfo.objectName || ''}</span>}
                            </Form.Item>

                            <Form.Item required={!isDetail} label="与录用者关系" key={`relateType-${key}`}>
                                {!isDetail &&
                                    getFieldDecorator(`relateType-${key}`, {
                                        initialValue: initialFormInfo.relateType
                                            ? String(initialFormInfo.relateType)
                                            : undefined,
                                        rules: [
                                            {
                                                required: true,
                                                message: '请选择或输入与录用者关系'
                                            }
                                        ]
                                    })(
                                        <AutoCompleteSelect
                                            disabled={canOnlyEditEvaluate}
                                            placeholder="请选择或输入"
                                            allowClear
                                            dataList={relateTypeList.map(item => ({
                                                label: item.dictName,
                                                value: item.dictName
                                            }))}
                                        />
                                    )}
                                {isDetail && (
                                    <span style={{ display: 'inline-block' }}>{initialFormInfo.relateType}</span>
                                )}
                            </Form.Item>
                            <Form.Item required={!isDetail} label="联系方式">
                                {!isDetail && (
                                    <Row gutter={8}>
                                        <Col span={6}>
                                            <Form.Item>
                                                {getFieldDecorator(`objectContactType-${key}`, {
                                                    initialValue: initialFormInfo.objectContactType
                                                        ? String(initialFormInfo.objectContactType)
                                                        : '1'
                                                })(
                                                    <Select
                                                        disabled={canOnlyEditEvaluate}
                                                        placeholder="请选择"
                                                        style={{ position: 'relative', top: '1px' }}
                                                    >
                                                        {objectContactTypeList.map(item => (
                                                            <Select.Option value={item.value}>
                                                                {item.label}
                                                            </Select.Option>
                                                        ))}
                                                    </Select>
                                                )}
                                            </Form.Item>
                                        </Col>
                                        <Col span={18}>
                                            <Form.Item>
                                                {getFieldDecorator(`objectContactInfo-${key}`, {
                                                    initialValue: initialFormInfo.objectContactInfo || undefined,
                                                    rules: [
                                                        {
                                                            required: true,
                                                            validator(rule, value, callback) {
                                                                if (!value) {
                                                                    callback('请输入联系方式');
                                                                }
                                                                if (
                                                                    form.getFieldValue(`objectContactType-${key}`) ===
                                                                    '1'
                                                                ) {
                                                                    const regex = /^\d+$/;
                                                                    if (value && !regex.test(value)) {
                                                                        callback('只能输入数字');
                                                                    }
                                                                }

                                                                callback();
                                                            }
                                                        }
                                                    ]
                                                })(
                                                    <Input
                                                        placeholder="请输入"
                                                        disabled={canOnlyEditEvaluate}
                                                        // 临时去掉显示区号，后期需要添加区号，则放开
                                                        // addonBefore={
                                                        //     havePhoneAreaType &&
                                                        //     getFieldDecorator(`phoneAreaType-${key}`, {
                                                        //         initialValue:
                                                        //             initialFormInfo.phoneAreaType ||
                                                        //             defaultPhoneAreaType
                                                        //     })(
                                                        //         <Select
                                                        //             disabled={canOnlyEditEvaluate}
                                                        //             placeholder="请选择区号"
                                                        //             place
                                                        //             style={{ width: 70 }}
                                                        //         >
                                                        //             <Select.Option value={1}>+86</Select.Option>
                                                        //             <Select.Option value={2}>+65</Select.Option>
                                                        //         </Select>
                                                        //     )
                                                        // }
                                                    />
                                                )}
                                            </Form.Item>
                                        </Col>
                                    </Row>
                                )}
                                {isDetail && getContactText()}
                            </Form.Item>
                            <BackgroundTimeItem backgroundType={backgroundType} {...props} />
                            <Form.Item {...fullRowLayout} span={24} label="对象介绍" key={`objectRemark-${key}`}>
                                {!isDetail &&
                                    getFieldDecorator(`objectRemark-${key}`, {
                                        initialValue: initialFormInfo.objectRemark,
                                        rules: [
                                            {
                                                required: false,
                                                max: 1000,
                                                message: '不能超过1000个字符'
                                            }
                                        ]
                                    })(<Input.TextArea maxLength={1000} rows={3} />)}
                                {isDetail && (
                                    <div className={styles.preText}>{initialFormInfo.objectRemark || '无'}</div>
                                )}
                            </Form.Item>
                            <EvaluateRemarkItem
                                backgroundType={backgroundType}
                                span={24}
                                label="评价"
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入评价'
                                    },
                                    {
                                        max: 400,
                                        message: '不能超过400个字符'
                                    }
                                ]}
                                fullRowLayout={fullRowLayout}
                                {...props}
                            />
                        </FormContainer>
                    )}
                    {backgroundType === 2 && (
                        <>
                            <FormContainer>
                                <OrganizationNameItem
                                    canOnlyEditEvaluate={canOnlyEditEvaluate}
                                    label="背调机构"
                                    inputRules={inputRules}
                                    placeholder="请输入背调机构"
                                    dataList={[]} // 背调机构不需要下来，用手动输入，传入空字符串
                                    {...props}
                                />
                                <Form.Item label="背调反馈方式" key={`feedbackState-${key}`}>
                                    {!isDetail &&
                                        getFieldDecorator(`feedbackState-${key}`, {
                                            initialValue: initialFormInfo.feedbackState || feedbackStateInfo[0].value,
                                            rules: [
                                                {
                                                    required: true,
                                                    message: '请选择背调反馈方式'
                                                }
                                            ]
                                        })(
                                            <Radio.Group onChange={e => form.setFieldsValue(e.target.value)}>
                                                {feedbackStateInfo.map(item => (
                                                    <Radio value={item.value} key={item.value}>
                                                        {item.text}
                                                    </Radio>
                                                ))}
                                            </Radio.Group>
                                        )}
                                    {isDetail && (
                                        <span>
                                            {
                                                feedbackStateInfo.find(
                                                    item => item.value === initialFormInfo.feedbackState
                                                )?.text
                                            }
                                        </span>
                                    )}
                                </Form.Item>
                                {(form.getFieldValue(`feedbackState-${key}`) === feedbackStateInfo[0].value ||
                                    (isDetail && initialFormInfo.feedbackState === feedbackStateInfo[0].value)) && (
                                    <>
                                        <Form.Item label="机构邮箱" key={`organizationEmail-${key}`}>
                                            {!isDetail &&
                                                getFieldDecorator(`organizationEmail-${key}`, {
                                                    initialValue: initialFormInfo.organizationEmail,
                                                    rules: [
                                                        {
                                                            required: true,
                                                            message: '请输入机构邮箱'
                                                        },
                                                        {
                                                            pattern: /^[A-Za-z0-9._-\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
                                                            message: '邮箱格式错误'
                                                        }
                                                    ]
                                                })(<Input placeholder="请输入机构邮箱"></Input>)}
                                            {isDetail && <span>{initialFormInfo.organizationEmail}</span>}
                                        </Form.Item>
                                    </>
                                )}
                            </FormContainer>
                            {/* 如果是详情页，无论什么背调反馈方式都要显示 */}
                            {(isDetail ||
                                form.getFieldValue(`feedbackState-${key}`) === feedbackStateInfo[1].value) && (
                                <FormContainer>
                                    <BackgroundTimeItem backgroundType={backgroundType} {...props} />
                                    <EvaluateRemarkItem
                                        backgroundType={backgroundType}
                                        span={24}
                                        label="背调结论"
                                        rules={[
                                            {
                                                required: true,
                                                message: '请输入背调结论'
                                            },
                                            {
                                                max: 400,
                                                message: '不能超过400个字符'
                                            }
                                        ]}
                                        fullRowLayout={fullRowLayout}
                                        {...props}
                                    />
                                </FormContainer>
                            )}
                        </>
                    )}
                    {(backgroundType === 3 || backgroundType === 99) && (
                        <FormContainer>
                            <OrganizationNameItem
                                canOnlyEditEvaluate={canOnlyEditEvaluate}
                                label="背调渠道"
                                inputRules={inputRules}
                                {...props}
                            />
                            <BackgroundTimeItem
                                backgroundType={backgroundType}
                                canOnlyEditEvaluate={canOnlyEditEvaluate}
                                {...props}
                            />
                            <EvaluateRemarkItem
                                backgroundType={backgroundType}
                                span={24}
                                label="内容"
                                fullRowLayout={fullRowLayout}
                                {...props}
                                rules={[
                                    {
                                        required: true,
                                        validator(rule, value, callback) {
                                            if (!value) {
                                                callback('内容不能为空');
                                            } else if (value.length > 400) {
                                                callback('不能超过400个字符');
                                            }
                                            callback();
                                        }
                                    }
                                ]}
                            />
                        </FormContainer>
                    )}
                </>
            </Row>
            <Row>{attachFileItem()}</Row>
        </div>
    );
};

export default BackgroundForm;
